package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.pojo.User;
import com.itheima.pojo.pageBean;
import com.itheima.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Test2.class);    // 创建Spring容器
    UserServiceImpl UserServiceImpl = (UserServiceImpl) applicationContext.getBean("userService");

      public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");

        String password = req.getParameter("password");

        User user = UserServiceImpl.select(username, password);

          if(user!=null){

              User user2 = new User();
              user2.setUsername(username);
              user2.setPassword(password);

            Cookie C_username = new Cookie("username",user.getUsername());
            Cookie C_password = new Cookie("password",user.getPassword());

            C_username.setMaxAge(60);
            C_password.setMaxAge(60);

            resp.addCookie(C_username);
            resp.addCookie(C_password);

            HttpSession session = req.getSession();
            session.setAttribute("user", user2);

              resp.getWriter().write("success");
          }else{
              resp.setContentType("text/html;charset=utf-8");
              resp.getWriter().write("用户名或密码错误");
          }

      }


}
